import _ from 'lodash';
import { toast } from '@/components/basicComp/Toast';
import { parse } from 'partial-json';

let str = '';

function setStr(newValue) {
  str = newValue;
}

function chatMsgWs(data, This) {
  var config = { data, This };
  var obj = data.data;
  const { selectedChat } = This.props;

  if (data.sub_type == 'ERROR') ERROR(config);

  // 没会话 不处理
  if (!selectedChat) return;

  var wsId = window.ws.config.uuid;

  // 不是当前网页的消息 不处理
  if (wsId != data.client_id) {
    return;
  }

  // 不是当前回话不处理
  if (obj.conversation_id != selectedChat) {
    return;
  }

  // 没说过话不处理
  if (!This.dialog_segment_id) {
    return;
  }

  console.log(data.sub_type, data);

  // 正常ai返回消息
  if (data.type == 'ASSISTANT_MESSAGE') ASSISTANT_MESSAGE(config);

  // 工具调用 开始
  if (data.sub_type == 'TOOL_CALL') TOOL_CALL(config);

  // 工具调用 结束
  if (data.sub_type == 'TOOL_CALL_RESULT') TOOL_CALL_RESULT(config);

  
}

var ASSISTANT_MESSAGE = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState,controller },
  } = This.props;


  if(This.dialog_segment_id != obj.dialog_segment_id){
    str = ''
    // 需要创建一条 新数据
    This.dialog_segment_id = obj.dialog_segment_id

    var store = window.getStore();
    var { ppt } = store.getState();

    // 添加用户消息
    var messages = [...ppt.messages];
    // 机器人空数据
    messages.push({
      role: 'assistant',
      content: [],
      object: null,
      initData: true,
    });
    changeState({ messages: messages });
  }


  // 正常情况
  if (data.group?.status == 'ENDED') {
    clearTimeout(This.heartbeatTimer);

    var jsonObj = parse(str);
    if(jsonObj.needs_plan){
      var PptOutline = controller.PptOutline
      if(PptOutline){
        PptOutline.getPlan()
      }
    }

    console.log('终止了');
    This.chatEnd();
    return;
  }

  This.chatTimeNext();

  // 处理消息
  if (obj.content) {
    str += obj.content;
    var jsonObj = parse(str);
    console.log(jsonObj)
   
    // 需要打印文字
    if(jsonObj.response){
      var text = jsonObj.response
      This.setMessage({
        role: 'ai',
        content: [
          {
            type: 'text',
            text: text,
            itemData: obj,
          },
        ],
        initData: false,
      });
    }

    // 处理任务
    if(jsonObj.needs_plan){
      var PptOutline = controller.PptOutline
      if(PptOutline && jsonObj.steps){
        PptOutline.wsSetList(jsonObj.steps)
      }
    }

    changeState({ chatLoading: true });
  }

};

var TOOL_CALL = (config) => {
  const { data, This } = config;
  var obj = data.data;

  const {
    value: { changeState, scrollToBottom2 },
  } = This.props;
  // 插入一条

  var store = window.getStore();
  var { ppt } = store.getState();

  setStr('');

  // 添加用户消息
  var messages = [...ppt.messages];

  // 机器人空数据
  messages.push({
    ...obj,
    role: 'ai',
    content: [],
    object: null,
    tool_calls: obj.tool_calls,
  });

  var toolObj = { ...ppt.toolObj };

  obj.tool_calls.forEach((item, i) => {
    toolObj[item.id] = item.id;
  });

  changeState({
    chatLoading: true,
    messages: messages,
    toolObj: toolObj,
  });

  This.scrollTime = setTimeout(() => {
    clearTimeout(This.scrollTime);
    scrollToBottom2();
  }, 20);

  console.log('TOOL_CALL');
  console.log(data);
};

var TOOL_CALL_RESULT = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState, scrollToBottom2 },
  } = This.props;

  setTimeout(() => {
    var store = window.getStore();
    var { ppt } = store.getState();

    var toolObj = { ...ppt.toolObj };
    obj.tool_calls.forEach((item, i) => {
      var id = item.tool_call_id;
      delete toolObj[id];
    });

    changeState({
      chatLoading: false,
      toolObj: toolObj,
    });

    This.scrollTime = setTimeout(() => {
      clearTimeout(This.scrollTime);
      scrollToBottom2();
    }, 20);
  }, 1500);
};

var ERROR = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState, scrollToBottom2 },
  } = This.props;
  toast.error(obj.message,5000);
  This.chatClose()
};

export { chatMsgWs, setStr, str };
export default { chatMsgWs, setStr, str };
